<template>
  <el-dialog title="采购订单新增" :close-on-click-modal="false" :visible.sync="visible" center fullscreen>
    <el-button class="miui-dialog-close-btn" @click="visible = false">关闭页面</el-button>
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="订单号" prop="billId">
            <el-input v-model="dataForm.billId" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="制造商" prop="supplyName">
            <el-input v-model="dataForm.supplyName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收入仓位" prop="inStockId">
            <el-select v-model="dataForm.inStockId">
              <el-option v-for="item in stockOptions" :key="item.id" :value="item.id" :label="item.name"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="memo">
            <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="dataForm.memo"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form :inline="true">
      <el-form-item><el-button size="mini" type="danger" @click="delTableData">删除</el-button></el-form-item>
      <el-form-item><el-button type="info" @click="printBarcode">打印条码</el-button></el-form-item>
    </el-form>
    <el-table v-if="dataForm.ctgId" :data="dataList" ref="multipleTable" border v-loading="dataListLoading" header-cell-class-name="miui-header-cell-style" show-summary :summary-method="getSummaries" @selection-change="handleSelectionChange">
      <el-table-column key="1" type="selection" width="55"></el-table-column>
      <el-table-column key="2" prop="code" label="商品代码" width="200"></el-table-column>
      <el-table-column key="3" prop="name" label="商品名称"></el-table-column>
      <el-table-column key="4" prop="spec" label="型号"></el-table-column>
      <el-table-column key="5" prop="mirrorBall" label="老花镜度数" v-if="dataForm.ctgId == 8"></el-table-column>
      <el-table-column key="6" prop="manufacturerColorNumber" label="厂家色号" v-if="[1,6,8].includes(dataForm.ctgId)"></el-table-column>
      <el-table-column key="7" label="框架材质" v-if="dataForm.ctgId == 1">
        <template slot-scope="scope">
          {{getValueByType(frameMaterialData,scope.row.frameMaterial)}}
        </template>
      </el-table-column>
      <el-table-column key="8" prop="goodsSize" label="框架尺寸" v-if="[1,6,8].includes(dataForm.ctgId)"></el-table-column>
      <el-table-column key="9" label="配件类型" v-if="dataForm.ctgId == 2">
        <template slot-scope="scope">
          {{getValueByType(accessoryTypeData,scope.row.accessoriesType)}}
        </template>
      </el-table-column>

      <el-table-column key="10" prop="mirrorBall" label="球镜" v-if="[3,4].includes(dataForm.ctgId)"></el-table-column>
      <el-table-column key="11" prop="columnMirror" label="柱镜" v-if="[3,4].includes(dataForm.ctgId)"></el-table-column>
      <el-table-column key="12" prop="toTheLight" label="下加光" v-if="dataForm.ctgId == 3"></el-table-column>
      <el-table-column key="13" prop="refractiveIndex" label="折射率" v-if="dataForm.ctgId == 3"></el-table-column>
      <el-table-column key="14" label="镜片分类" v-if="dataForm.ctgId == 3">
        <template slot-scope="scope">
          {{getValueByType(bizData.photometricClassification,scope.row.photometricClassification)}}
        </template>
      </el-table-column>
      <el-table-column key="15" label="材料分类" v-if="dataForm.ctgId == 3">
        <template slot-scope="scope">
          {{getValueByType(bizData.lensMaterial,scope.row.lensMaterial)}}
        </template>
      </el-table-column>

      <el-table-column key="16" prop="curvature" label="曲率" v-if="dataForm.ctgId == 4"></el-table-column>
      <el-table-column key="17" prop="diameter" label="直径" v-if="dataForm.ctgId == 4"></el-table-column>
      <el-table-column key="18" prop="useType" label="使用类型" v-if="dataForm.ctgId == 4"></el-table-column>
      <el-table-column key="19" prop="disusedClassification" label="抛弃类型" v-if="dataForm.ctgId == 4"></el-table-column>

      <el-table-column key="20" prop="primaryCapacity" label="主容量" v-if="dataForm.ctgId == 5"></el-table-column>
      <el-table-column key="21" prop="secondaryCapacity" label="次容量" v-if="dataForm.ctgId == 5"></el-table-column>

      <el-table-column key="22" label="效期" v-if="[4,5].includes(dataForm.ctgId)">
      	<template slot-scope="scope">
          <el-input v-model="scope.row.invalidTimeStr" size="mini" @change="invalidTimeChange(scope.row)" style="width: 90px;"></el-input>
      	</template>
      </el-table-column>
      <el-table-column key="23" label="批号" width="120" v-if="[4,5].includes(dataForm.ctgId)">
      	<template slot-scope="scope">
      		<el-input size="mini" v-model="scope.row.batch"></el-input>
      	</template>
      </el-table-column>
      <el-table-column key="24" label="注册证号" v-if="[4,5].includes(dataForm.ctgId)">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.registerNum"></el-input>
        </template>
      </el-table-column>
      <el-table-column key="25" label="商品条码" v-if="[4,5].includes(dataForm.ctgId)" width="270">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.goodsBarcode" readonly></el-input>
        </template>
      </el-table-column>
      <el-table-column key="26" prop="goodsBarcode" width="270" label="商品条码" v-if="dataForm.ctgId != 4 && dataForm.ctgId != 5"></el-table-column>
      <el-table-column key="27" label="数量" width="50">
        <template slot-scope="scope">
          <el-input v-model="scope.row.applyQuantity" :ref="'number'+scope.$index" @keyup.enter.native="enterChange(scope.$index)"></el-input>
        </template>
      </el-table-column>
    </el-table>

<!--  -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" @click="dataFormSubmit" :loading="ischeck" v-prevent-re-click>保存</el-button>
      <el-switch v-if="permissions.eims_inventory_audit"  v-model="dataForm.inveStatus" active-text="保存并审核" inactive-value="0" active-value="1" style="margin-left: 15px;"></el-switch>
    </span>
  </el-dialog>
</template>

<script>
    import { mapGetters } from 'vuex'
    import { checkDate } from '@/util/tools'
    import { getNowTime } from '@/api/eims/sale'
    import { remote } from '@/api/admin/dict'
    import { receiveApplyGetObj } from '@/api/eims/purchase/receive-apply'
    import { getStockList } from '@/api/eims/stock'
    import { receiveGoodsAddObj } from '@/api/eims/purchase/receive-goods'
    import { PrintBarcode } from '@/util/printDs'
    export default {
    data () {
      return {
				ischeck: false,
        visible: false,
        dataForm: {
          id: 0,
          ctgId: '',
          ctgName: '',
          inStockId: '',
          stockName: '',
          supplyId: '',
          supplyName: '',
          memo: '',
          detailList: [],
          frameMaterialData: [],
          accessoryTypeData: [],
        },
        dataRule: {
          inStockId: [{ required: true, message: '请选择收入仓库', trigger: 'blur' }]
        },
        stockOptions: [],
        dataList: [],
        dataListLoading: false,
        selectionList: []
      }
    },
    computed: {
      ...mapGetters(['bizData','permissions','userInfo'])
    },
    methods: {
      // 获取当前时间
      async getNowDateStr(){
        let nowDateStr = ''
        await getNowTime().then(result => {
          nowDateStr = result.data.data
        })
        return nowDateStr
      },
      init (id) {
        remote('frame_material').then(result => {
          this.frameMaterialData = result.data.data
        })
        remote('accessory_type').then(result => {
          this.accessoryTypeData = result.data.data
        })
        this.getStockList()
        this.dataForm.id = id || 0
        this.visible = true
        this.dataList = []
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            receiveApplyGetObj(this.dataForm.id).then(response => {
              if(response.data.code == '0'){
                let resultData = response.data.data.data
                this.dataForm = resultData
                this.dataList = resultData.detailList
                this.dataList.forEach(item => {
                  item.name = item.goodsName
                  item.code = item.goodsCode
                  if(item.ctgId == 4 || item.ctgId == 5){
                    item.goodsBarcode = item.code.replace(/[\ |\.]/g,"") + ((item.invalidTimeStr ) ? (item.invalidTimeStr .replace(/[\ |\-]/g,"")).substring(2,10) : '000000') + 'A0'
                  }else{
                    item.goodsBarcode = item.code.replace(/[\ |\.]/g,"") + ((item.invalidTimeStr ) ? (item.invalidTimeStr .replace(/[\ |\-]/g,"")).substring(2,10) : '00000000')
                  }

                })
              }else{
                this.$message.error(response.data.msg)
              }
            })
          }
        })
      },
      // 商品类别改变时获取名字
      ctgSelectChange ($event) {
        this.ctgOptions.forEach(item => {
          if(item.value == $event){ this.dataForm.ctgName = item.name }
        })
      },
      handleSelectionChange(val) {
        this.selectionList = val
      },
      // 删除选中的商品
      delTableData() {
        this.selectionList.forEach((item,index) => {
          for(let i = 0; i < this.dataList.length; i++){
            if(this.dataList[i] == item){
              this.dataList.splice(i,1)
            }
          }
          this.selectionList = []
        })
      },
      // 打印条码
      printBarcode(){
        let that = this
        if(this.selectionList.length < 1){
          alert("请钩选要打印的商品条码！");
          return false
        }
        if(confirm("条码打印确认！")){
          PrintBarcode(that)
        }
      },
      //更新表单数据
      updateFormData(data) {
        this.dataList = data
        data.forEach(item => {
          let list = []
          list.push({goodsId: item.id})
          this.dataForm.detailList = list
        })
      },
      //  回车切换下一行商品数量
      enterChange(index){
        if(this.$refs['number'+(index*1 + 1)]){
          this.$refs['number'+(index*1 + 1)].focus()
        }
      },
      // 表单提交
      dataFormSubmit () {
        if (this.dataForm.ctgId ==4 || this.dataForm.ctgId==5) {
          for(let i=0;i<this.dataList.length;i++){
            if(!this.dataList[i].invalidTimeStr){
              this.$message.warning("请输入效期");
              return;
            }
            if(!this.dataList[i].batch){
              this.$message.warning("请输入批号")
              return
            }
            if(!this.dataList[i].registerNum){
              this.$message.warning("请输入注册证号")
              return
            }
          }
        }
				this.ischeck = true
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.dataForm.detailList.forEach((item,index) => {
              item.quantity = this.dataList[index].applyQuantity
            })
            this.dataForm.inventoryApplyId = this.dataForm.id
            receiveGoodsAddObj(this.dataForm).then(response => {
              if(response.data.code == '0'){
                (this.dataForm.inveStatus == '1') ? this.$message.success('新增并审核成功') : this.$message.success('新增成功')
                this.visible = false
                this.$emit('refreshDataList')
              }else{
                this.$message.error(response.data.msg)
              }
              this.ischeck = false
            }).catch(() => {
							this.ischeck = false
						})
          }else{
						this.ischeck = false
					}
        })
      },

      // 获取仓位列表
      getStockList() {
        getStockList().then(response => {
          if(response.data.code == '0'){
            this.stockOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      getValueByType(data,key){
        let obj = {}
        obj = data.find(item => {
          return item.value == key
        })
        if(obj && obj.label){
          return obj.label
        }
      },
      //  效期改变事件
      invalidTimeChange(data){
        this.getNowDateStr().then(result => {
          if(checkDate(data.invalidTimeStr)){
            if(new Date(data.invalidTimeStr).getTime() > new Date(result).getTime()){
              let goodsId = data.id
              let code = data.code.replace(/[\ |\.]/g,"") + ((data.invalidTimeStr ) ? (data.invalidTimeStr .replace(/[\ |\-]/g,"")).substring(2,10) : '00000000') + 'A0'
              this.$set(data,'goodsBarcode',code);
              this.dataList = [...this.dataList]
            }else{
              data.invalidTimeStr = ''
              this.$message.warning('效期不可小于当前日期')
            }
          }else{
            data.invalidTimeStr = ''
            this.$message.error('请填写正确日期格式 2020-01-01')
            return false
          }
        })
      },
      //  合计
      getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            let zIndex = ''
            if([1,8].includes(this.dataForm.ctgId)){
              zIndex = 8
            }else if([2].includes(this.dataForm.ctgId)){
              zIndex = 6
            }else if([3,4].includes(this.dataForm.ctgId)){
              zIndex = 11
            }else if([5,6].includes(this.dataForm.ctgId)){
              zIndex = 7
            }else if([7,9].includes(this.dataForm.ctgId)){
              zIndex = 5
            }
            if(index == zIndex){
              sums[index] = '合计： ' + values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0)
            }

          }
        });
        return sums;
      }
    }
  }
</script>
<style lang="scss" scoped>
  /deep/ .el-table {
  display: flex;
  flex-direction: column;
  }

  /deep/ .el-table__body-wrapper {
  order: 1;
  }
</style>
